package com.bawan.vims.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p> Title        : ValidateCodeServlet.java </p>
 * <p> Description	: ValidateCodeServlet.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: JOCHEN ZHENG </p>
 * <p> Create		: 2015-1-5 11:31:52 </p> 
 * <p> version 		: 1.0 </p>
 */
public class ValidateCodeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger log = LoggerFactory.getLogger(ValidateCodeServlet.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		try {
			randomValidateCode.getRandcode(request, response);// 输出图片方法
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param fileToDownload 下载的文件路径
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileToDownload) throws IOException{
		final int BYTES = 1024;
		int length = 0;
		
		ServletOutputStream out = response.getOutputStream();
		ServletContext context = getServletConfig().getServletContext();
		
		String mimeType = context.getMimeType("fileToDownload");
		response.setContentType(mimeType != null ? mimeType : "text/plain");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileToDownload );
		
		InputStream in = context.getResourceAsStream("/" + fileToDownload);
		
		byte[] buffer = new byte[BYTES];
		
		while((in != null) && ((length = in.read(buffer)) != -1)) {
			out.write(buffer, 0, length);
		}
		
		out.flush();
		out.close();
	}
}
